cmake_minimum_required(VERSION 3.10)
project(tcu VERSION 1.0.0 LANGUAGES C)

# 设置C标准
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)

# 编译选项
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -O2")

# 设置输出目录
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../out/tcu)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../out/tcu)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../out/tcu)

# 查找依赖包
find_package(PkgConfig REQUIRED)
find_package(Threads REQUIRED)

# 使用本地cJSON源码
set(CJSON_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../third_party/cJSON)
set(CJSON_INCLUDE_DIR ${CJSON_SOURCE_DIR})
set(CJSON_SOURCES ${CJSON_SOURCE_DIR}/cJSON.c)

# 查找OpenSSL
pkg_check_modules(OPENSSL REQUIRED openssl)

# 查找Paho MQTT C库
find_library(PAHO_MQTT_C_LIB paho-mqtt3c)
if(NOT PAHO_MQTT_C_LIB)
    message(FATAL_ERROR "Paho MQTT C library not found. Please install libpaho-mqtt-dev")
endif()

# 包含目录
include_directories(
    ${CMAKE_CURRENT_SOURCE_DIR}/include
    ${CMAKE_CURRENT_SOURCE_DIR}/../include
    ${CMAKE_CURRENT_SOURCE_DIR}/../../include
    ${CMAKE_CURRENT_SOURCE_DIR}/../../src
    ${CJSON_INCLUDE_DIR}
    ${OPENSSL_INCLUDE_DIRS}
)

# 源文件
set(TCU_SOURCES
    src/tcu.c
    src/config_manager.c
    src/main.c
    ../../src/logger.c
    ${CJSON_SOURCES}
)

# 头文件
set(TCU_HEADERS
    include/tcu.h
    include/config_manager.h
)

# 创建可执行文件
add_executable(tcu ${TCU_SOURCES} ${TCU_HEADERS})

# 链接库
target_link_libraries(tcu
    ${PAHO_MQTT_C_LIB}
    ${OPENSSL_LIBRARIES}
    Threads::Threads
    m
)

# 编译定义
target_compile_definitions(tcu PRIVATE
    TCU_VERSION="${PROJECT_VERSION}"
    TCU_BUILD_DATE="${CMAKE_CURRENT_SOURCE_DIR}"
)

# 安装规则
install(TARGETS tcu DESTINATION bin)
install(DIRECTORY config/ DESTINATION share/tcu/config)
install(DIRECTORY include/ DESTINATION include/tcu)

# 测试
enable_testing()
add_subdirectory(tests)
